import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:abc/model/point_model.dart';

class PointTaskController extends GetxController with GetSingleTickerProviderStateMixin{
  // 添加一个响应式变量来跟踪选中的标签索引
  final selectedIndex = 0.obs;

// --- TabBar 控制器 ---
  late TabController tabController;
  final List<String> tabs = ['积分任务', '积分商城'];

  // --- Rx 响应式状态 ---
  final userInfo = UserInfo(name: '爱吃菠菜的大力水手', points: 324).obs;
  final taskList = <PointTask>[].obs;
  final productList = <PointProduct>[].obs;

  @override
  void onInit() {
    super.onInit();
    tabController = TabController(length: tabs.length, vsync: this);
    
    // 添加监听器来跟踪标签切换
    tabController.addListener(_handleTabSelection);
    
    // 模拟从服务器获取数据
    _loadTasksFromMockServer();
    _loadProductsFromMockServer();
  }

  // 处理标签选择变化
  void _handleTabSelection() {
    if (!tabController.indexIsChanging) {
      selectedIndex.value = tabController.index;
    }
  }

  @override
  void onClose() {
    tabController.removeListener(_handleTabSelection);
    tabController.dispose();
    super.onClose();
  }

  // ============== 模拟积分任务数据 (来自图片左侧) ==============
  void _loadTasksFromMockServer() {
    // 实际应用中这里会调用API并解析JSON
    taskList.assignAll([
      PointTask(
        title: '每日登录',
        subtitle: '(1/1)',
        reward: '10',
        buttonText: '已领取',
        icon: 'ic_mrdl',
        isCompleted: true, // 已领取
      ),
      PointTask(
        title: '观看影片',
        subtitle: '(3/2)',
        reward: '10',
        buttonText: '去完成',
        icon: 'ic_gkyp',
        isCompleted: false, // 去完成
      ),
      PointTask(
        title: '邀请用户',
        subtitle: '(3/2)',
        reward: '10',
        buttonText: '领取',
        icon: 'ic_yqyh',
        isCompleted: false, // 领取 (已完成任务但未领取奖励)
      ),
      PointTask(
        title: '用户评论',
        subtitle: '(3/2)',
        reward: '10',
        buttonText: '领取',
        icon: 'ic_yhpl',
        isCompleted: false, // 领取
      ),
    ]);
  }

  // ============== 模拟积分商城数据 (来自图片右侧) ==============
  void _loadProductsFromMockServer() {
    // 实际应用中这里会调用API并解析JSON
    productList.assignAll([
      PointProduct(
        title: 'VIP3天',
        subtitle: '(200积分)',
        pointsCost: '200积分可兑换3天VIP',
        buttonText: '已领取',
        isRedeemed: true, // 已领取
      ),
      PointProduct(
        title: '2000金币',
        subtitle: '(200积分)',
        pointsCost: '200积分可兑换2000金币',
        buttonText: '领取',
        isRedeemed: false, // 领取
      ),
      PointProduct(
        title: '月会员卡',
        subtitle: '(300积分)',
        pointsCost: '300积分可兑换1个月会员卡',
        buttonText: '领取',
        isRedeemed: false, // 领取
      ),
    ]);
  }

  // 模拟领取/兑换操作
  void redeemTask(PointTask task) {
    Get.snackbar('操作成功', '已领取/完成 ${task.title}');
    // 实际应用中更新 taskList 状态
  }

  void redeemProduct(PointProduct product) {
    Get.snackbar('操作成功', '已兑换 ${product.title}');
    // 实际应用中更新 productList 状态
  }
}